package org.ww.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;

import org.ww.product.dao.CategoryDao;
import org.ww.product.entity.CategoryEntity;
import org.ww.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }
    //查询所有的商品列表，包括子分类
    @Override
    public List<CategoryEntity> listQueryTree() {
        //首先查询所有的商品分类
        List<CategoryEntity> all = baseMapper.selectList(null);
        //1 查询一级分类及所有子分类
        List<CategoryEntity> level1Emnu = all.stream().filter(categoryEntity ->
            categoryEntity.getParentCid() == 0
        ).map((emnu)->{
            emnu.setChildren(getChildren(emnu,all));
            return emnu;
        }).sorted((emnu1,emnu2)->
                (emnu1.getSort()==null?0:emnu1.getSort())-(emnu2.getSort()==null?0:emnu2.getSort())
        ).collect(Collectors.toList());
        return level1Emnu;
    }

    @Override
    public void removeBatch(List<Long> longs) {
        //TODO 删除之前需要判断哪些菜单被引用了
        baseMapper.deleteBatchIds(longs);
    }

    public List<CategoryEntity> getChildren(CategoryEntity categoryEntity,List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream().filter(entity ->
                categoryEntity.getCatId() == entity.getParentCid()
        ).map((emnu)->{
            emnu.setChildren(getChildren(emnu,all));
            return emnu;
        }).sorted((emnu1,emnu2)->
                (emnu1.getSort()==null?0:emnu1.getSort())-(emnu2.getSort()==null?0:emnu2.getSort())
        ).collect(Collectors.toList());
        return collect;
    }

}